package com.pat.web.controller;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;

import com.jfinal.core.Controller;
import com.jfinal.render.JsonRender;
import com.pat.common.Constants;
import com.pat.web.ApiResponse;
import com.pat.web.model.MailValidcode;
import com.pat.web.model.User;

public class UserCenterController extends Controller {

	public static final String EMAIL_ACCOUNT = "Petnote@petnote.cn";
	public static final String EMAIL_PASSWORD = "GuanFangYouXiang2017";
	public static final String SMTP_HOST = "smtp.exmail.qq.com";
	public static final String SMTP_PORT = "465";

	public void updateUser() {
		User user = getBean(User.class, "", true);
		String nick_name = getPara("nick_name");
		if (StringUtils.isNotBlank(nick_name)) {
			user.setNickName(nick_name);
		}
		Long countyId = getParaToLong("county_id");
		if (countyId != null) {
			user.setCountyId(countyId);
		}
		Long provinceId = getParaToLong("province_id");
		if (provinceId != null) {
			user.setProvinceId(provinceId);
		}
		Long cityId = getParaToLong("city_id");
		if (cityId != null) {
			user.setCityId(cityId);
		}
		Long userid = getAttr(Constants.LOGIN_USER_ID);

		String oldPassword = getPara("oldPassword");
		User existed = User.dao.findFirst("select * from user where id = ?", userid);
		if (oldPassword != null && !"".equals(oldPassword)) {
			String shaPassword = DigestUtils.sha256Hex(oldPassword);
			if (existed == null || !existed.getPassword().equals(shaPassword)) {
				ApiResponse response = new ApiResponse();
				response.setStatusCode("1005");
				render(new JsonRender(response));
				return;
			}
			String password = user.getPassword();
			String digestPWD = DigestUtils.sha256Hex(password.getBytes());
			user.setPassword(digestPWD);
		} else {
			user.setPassword(existed.getPassword());
		}
		user.setId(userid);
		user.setUpdateTime(new Date());
		user.update();

		ApiResponse response = new ApiResponse();
		response.setStatusCode("0000");

		User output = getOutputUserById(userid);
		response.setData(output);
		render(new JsonRender(response));
	}

	public void changePhone() {
		User user = getBean(User.class, "");

		String storedKey = user.getMobile() + "_sms" + (System.currentTimeMillis() / 1000 / 60 / 5);
		String code = getPara("code");
		String sessionCode = getSessionAttr(storedKey);
		if (code == null || !code.equals(sessionCode)) {
			ApiResponse response = new ApiResponse();
			response.setStatusCode("1003");
			render(new JsonRender(response));
			return;
		}
		Long userid = getAttr(Constants.LOGIN_USER_ID);
		user.setId(userid);
		user.setUpdateTime(new Date());
		user.update();

		ApiResponse response = new ApiResponse();
		response.setStatusCode("0000");

		User output = getOutputUserById(userid);
		response.setData(output);
		render(new JsonRender(response));

	}

	private User getOutputUserById(Long userid) {
		return User.dao.findByIdLoadColumns(userid,
				"mobile,email,nick_name,photo,sex,birthday,sign,province_id,city_id,county_id");
	}

	public void userInfo() {
		Long userid = getAttr(Constants.LOGIN_USER_ID);
		ApiResponse response = new ApiResponse();
		response.setStatusCode("0000");
		User output = getOutputUserById(userid);
		response.setData(output);
		render(new JsonRender(response));
	}

	public void sendMessageToMail() {
		String email = getPara("email");
		ApiResponse response = new ApiResponse();
		String regEx = "[a-zA-Z_0-9]{1,}@(([a-zA-z0-9]-*){1,}\\.){1,3}[a-zA-z\\-]{1,}";
		Pattern pattern = Pattern.compile(regEx);
		Matcher matcher = pattern.matcher(email);
		if (StringUtils.isBlank(email) || !matcher.matches()) {
			response.setStatusCode("1007");
			render(new JsonRender(response));
			return;
		}
		Random r = new Random();
		int code = r.nextInt(900000) + 100000;
		String subject = "宠物手帐验证码";
		String content = "尊敬的宠物手帐用户，您的绑定安全邮箱验证码为：%s，请在宠物手帐APP中输入进行绑定操作。";
		content = String.format(content, code);

		Long userid = getAttr(Constants.LOGIN_USER_ID);
		User user = User.dao.findById(userid);

		Properties props = new Properties();
		props.setProperty("mail.transport.protocol", "smtp");
		props.setProperty("mail.smtp.host", SMTP_HOST);
		props.setProperty("mail.smtp.port", SMTP_PORT);
		props.setProperty("mail.smtp.auth", "true");
		props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
		props.setProperty("mail.smtp.socketFactory.fallback", "false");
		props.setProperty("mail.smtp.socketFactory.port", SMTP_PORT);
		Session session = Session.getDefaultInstance(props);
		MimeMessage message = new MimeMessage(session);
		try {
			message.setFrom(new InternetAddress(EMAIL_ACCOUNT, "宠物手帐", "UTF-8"));
			message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(email, user.getNickName(), "UTF-8"));
			message.setSubject(subject, "UTF-8");
			message.setContent(content, "text/html;charset=UTF-8");
			message.setSentDate(new Date());
			message.saveChanges();

			Transport transport = session.getTransport();
			transport.connect(EMAIL_ACCOUNT, EMAIL_PASSWORD);
			transport.sendMessage(message, message.getAllRecipients());
			transport.close();
		} catch (UnsupportedEncodingException | MessagingException e) {
			e.printStackTrace();
			response.setStatusCode("1008");
			render(new JsonRender(response));
			return;
		}
		new MailValidcode().setUserId(userid).setMailAddress(email).setValidcode(code).setUsed(0)
				.setCreateTime(new Date()).save();
		response.setStatusCode("0000");
		render(new JsonRender(response));
	}

	public void bindEmail() {
		String email = getPara("email");
		String code = getPara("code");
		Long userId = getAttr(Constants.LOGIN_USER_ID);
		ApiResponse response = new ApiResponse();

		String regEx = "[a-zA-Z_0-9]{1,}@(([a-zA-z0-9]-*){1,}\\.){1,3}[a-zA-z\\-]{1,}";
		Pattern pattern = Pattern.compile(regEx);
		Matcher matcher = pattern.matcher(email);
		if (StringUtils.isBlank(email) || !matcher.matches()) {
			response.setStatusCode("1007");
			render(new JsonRender(response));
			return;
		}

		MailValidcode mailValidcode = MailValidcode.dao.findFirst(
				"select * from mail_validcode where user_id = ? and mail_address = ? and validcode = ? and used = 0",
				userId, email, code);
		if (mailValidcode != null) {
			User user = User.dao.findById(userId);
			user.setEmail(email).update();
			mailValidcode.setUsed(1).update();
			response.setStatusCode("0000");
			response.setData(user);
			render(new JsonRender(response));
			return;
		}
		response.setStatusCode("1009");
		render(new JsonRender(response));
	}
}
